<!--
 * @Author: 卡卡 1071780426@qq.com
 * @Date: 2022-11-04 11:41:30
 * @LastEditors: 贺楠 1071780426@qq.com
 * @LastEditTime: 2024-04-01 10:17:08
 * @FilePath: \backstage - 副本\src\components\public\pdf-dialog.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <div>
    <!--  -->
    <el-dialog
      top="38vh"
      class="uploadWidth"
      append-to-body
      :title="titleText"
      v-dialogDrag
      :visible.sync="dialogUploads"
      v-loading="loadingUploads"
      @close="closeDialogs"
    >
    <!-- :auto-upload="false":on-change="handleChange" -->
      <div class="dialogBody common" style="height: 240px">
        <el-upload
          action="action"
          ref="upload"
          list-type="picture-card"
          :file-list="fileList"
          :accept="filetype"
 
          :before-upload="handleSuccess"
        >
          <!--  -->
          <!--   -->
          <i slot="default" class="el-icon-plus"></i>
          <div
            style="width: 100%; height: 100%; text-align: center"
            slot="file"
            slot-scope="{ file }"
          >
            <div
              style="
                width: 100%;
                height: 100%;
                display: flex;
                justify-content: center;
                align-items: center;
              "
              class="images"
              v-if="fileNum == 1"
            >
              <img
                style="max-width: 100%; max-height: 100%"
                src="@/assets/img/pdf.png"
              />
            </div>

            <div
              style="
                width: 100%;
                height: 100%;
                display: flex;
                justify-content: center;
                align-items: center;
              "
              class="images"
              v-viewer
              v-else-if="fileNum == 0"
            >
              <img style="max-width: 100%; max-height: 100%" :src="file.url" />
            </div>
            <span class="el-upload-list__item-actions">
              <span
                v-if="fileNum == 1"
                title="文件预览"
                class="el-upload-list__item-preview"
                @click="openPdf(file)"
              >
                <i class="el-icon-zoom-in"></i>
              </span>
              <span
                v-else-if="fileNum == 0"
                title="照片预览"
                class="el-upload-list__item-preview"
                @click="handlePictureCardPreview(file)"
              >
                <i class="el-icon-zoom-in"></i>
              </span>
              <!--  -->
              <span
                :title="title"
                class="el-upload-list__item-delete"
                @click="handleRemove(file)"
              >
                <i class="el-icon-delete"></i>
              </span>
            </span>
          </div>
        </el-upload>
        <div>
          <div style="position: absolute; right: 15px; bottom: 10px">
            <el-button type="primary" @click="submitUpload(enclosureImg)"
              >保存</el-button
            >
          </div>
        </div>
      </div>
    </el-dialog>

    <pdfDialog
      :dialogVisible="dialogVisibles"
      @closes="dialogVisibles = false"
      :fileDetail="fileDetail"
    ></pdfDialog>
  </div>
</template>
<script>
import pdfDialog from "@/components/public/pdf-dialogs";
import { upload,fileAnnexes } from "@/api/request.js";
export default {
  props: {
    // 0：上传照片 1：上传文件
    fileType: {
      type: String,
      default: "0",
      // default: '.jpg, .jpeg, .png, .gif, .bmp, .JPG, .JPEG, .PBG, .GIF, .BMP',
    },
    // pdf
    dialogVisibles: {
      type: Boolean,
      default: false,
    },
    // pdf
    fileDetail: {
      type: Object,
      default: () => {},
    },
    // 上传文件
    dialogUpload: {
      type: Boolean,
      default: false,
    },
    // 默认文件
    fileArray: {
      type: Array,
      default: () => [],
    },
    folderid: {
      type: String,
      default: "",
    },
  },
  components: {
    pdfDialog,
  },

  // fileType
  data() {
    return {
      // 附件名称
      fFileName: null,
      // 附件地址
      pdfUrl: null,
      // 附件展示
      dialogPdf: false,
      loadingDialogTexts: false,
      enclosureImg: {},
      fileList: [], //文件列表
      recordfiles: [], //删除文件id集合
      titleText: "上传照片",
      dialogUploads: false,
      loadingUploads: false,
      filetype: ".jpg, .jpeg, .png, .gif, .bmp, .JPG, .JPEG, .PBG, .GIF, .BMP",
      fileNum: "0",
      title: "删除照片",
      userInfo: {},
    };
  },
  watch: {
    fileType: {
      handler(newVal) {
        // console.log(newVal);
        // jpg/jpeg
// png
        if (newVal == 0) {
          this.fileNum = 0;
          this.filetype =
            ".jpg, .jpeg, .png";
          this.title = "删除照片";
          this.titleText = "上传照片";

          // this.pdfUrl = newVal.url;
          // this.fFileName = newVal.fFileName;
        } else if (newVal == 1) {
          // this.filetype =
          //   ".pdf,.txt,.doc,.docx,.xls,.xlsx,.rft,.rar,.dat,.key,.msg,.cad,.btw,.avi,.rmvb,.wps,.et,.dps,.vsd,.prn,.dib,.ico";
          this.filetype = ".pdf";
          this.fileNum = 1;
          this.title = "删除文件";
          this.titleText = "上传文件";
        }
      },
      immediate: true,
    },
    fileDetail: {
      handler(newVal) {
        // console.log(newVal);
        if (newVal) {
          this.pdfUrl = newVal.url;
          this.fFileName = newVal.fFileName;
        }
      },
      immediate: true,
    },
    dialogVisible: {
      handler(newVal) {
        if (newVal) {
          this.dialogPdf = this.dialogVisible;
          // console.log(this.dialogPdf);
        }
      },
      immediate: true,
    },
    dialogUpload: {
      handler(newVal) {
        // console.log(newVal);
        if (newVal) {
          this.dialogUploads = this.dialogUpload;
          // console.log(this.dialogPdf);
        }
      },
      immediate: true,
    },
    fileArray: {
      handler(newVal) {
        // console.log(newVal);
        if (newVal) {
          this.fileList = this.fileArray;
          // console.log(this.dialogPdf);
        }
      },
      immediate: true,
    },
  },
  created() {
    this.userInfo = JSON.parse(sessionStorage.getItem("userInfo"));
  },
  mounted() {
    this.dialogPdf = this.dialogVisible;
    this.dialogUploads = this.dialogUpload;
  },

  methods: {
    closeDialog() {
      this.$emit("closes");
    },
    closeDialogs() {
      this.$emit("closes");
    },
    // beforeAvatarUpload(file) {
    //   console.log(222, file);

    // },

    // 上传文件之前的钩子，参数为上传的文件，若返回 false 或者返回 Promise 且被 reject，则停止上传。
    handleSuccess(file){
 
      var fileName=file.name;
      var flag;
      if(this.fileType==0){//照片
  
        flag= fileName.includes('.jpg')||fileName.includes('.JPG')||fileName.includes('.jpeg')||fileName.includes('.JPEG')||fileName.includes('.png')||fileName.includes('.PNG');
      }else if(this.fileType==1){
        flag= fileName.includes('.pdf')||fileName.includes('.PDF')
      }
      if(flag) {
        this.enclosureImg = new FormData(); //new一个formData事件
      this.enclosureImg.append("file", file); //将file属性添加到formData里
      this.enclosureImg.append("folderid", this.folderid); //将file属性添加到formData里
      this.enclosureImg.append("userId", this.userInfo.userId); //将file属性添加到formData里
      this.enclosureImg.append("userName", this.userInfo.realName); //将file属性添加到formData里
      this.loadingUploads = true;
      upload(this.enclosureImg)
        .then((i) => {
   
          if (i[0].code == "200") {
            this.loadingUploads = false;
            i[0]["name"] = file.name;
            // D:/fileAnnexes/20240328/fd094f8e-0b26-42f8-8e92-de6eb8bbc033/84c3d939-22cc-4bae-9147-5654e2e1f5d7.pdf
            i[0]["url"] =fileAnnexes +i[0].atta.fFilepath;
            this.fileList.push(i[0]);
          } else if(i[0].code == "405"){
            this.$message.error(i[0].atta.message);
          }else {
            this.$message.error("上传失败");
            this.loadingUploads = false;
          }
        })
        .catch(() => {
          console.log("上传文件接口失败");
          this.loadingUploads = false;
        });
      }else {
        this.$message.error("当前文件格式不支持");
      }
    },

    // 上传照片
    handleChange(res) {
      console.log(234, res);
      // const typeExtensions= ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'JPG', 'JPEG', 'PBG', 'GIF', 'BMP','jfif','jpe']; // 可以自定义需要支持的音频格式
      //   const fileExtension = res.name.split('.').pop().toLowerCase(); // 根据文件名获取文件扩展名并转换为小写字母形式
      //   if (typeExtensions.includes(fileExtension) == false) {
      //    console.log(this.fileList);
      //     // this.fileList.splice(this.fileList.length-1,1)
      //     this.$message.warning("上传图片格式只能是jpg/jpeg/png/gif/bmp/JPG/JPEG/PBG/GIF/BMP/jfif/jpe")
      //   }else {

      // return typeExtensions.includes(fileExtension);

      this.enclosureImg = new FormData(); //new一个formData事件
      this.enclosureImg.append("file", res.raw); //将file属性添加到formData里
      this.enclosureImg.append("folderid", this.folderid); //将file属性添加到formData里
      this.enclosureImg.append("userId", this.userInfo.userId); //将file属性添加到formData里
      this.enclosureImg.append("userName", this.userInfo.realName); //将file属性添加到formData里
      this.loadingUploads = true;
      upload(this.enclosureImg)
        .then((i) => {
          if (i[0].code == "200") {
            this.loadingUploads = false;
            i[0]["name"] = res.name;
            i[0]["url"] = res.url;
            this.fileList.push(i[0]);
          }else if(i[0].code == "405"){
            this.$message.error(i[0].message);
          } else {
            this.$message.error("上传失败");
            this.loadingUploads = false;
          }
        })
        .catch(() => {
          console.log("上传文件接口失败");
          this.loadingUploads = false;
        });
   
    },
    // 预览
    openPdf(val) {
      // console.log(val);
      this.dialogVisibles = true;
      this.fileDetail = val;
    },
    handleRemove(file) {
      // console.log(file);
      this.$emit("delteFile", file);
      // this.$refs.upload.handleRemove(file);
      // for (let index = 0; index < this.attachmentDetails.length; index++) {
      //   if (file.uid == this.attachmentDetails[index].uid) {
      //     this.imgsFId.fId = this.imgList[index][0].atta.fId;
      //     this.recordfilesList.push(this.imgsFId);
      //     this.formData.recordfiles = this.recordfilesList;
      //   }
      // }

      this.$refs.upload.handleRemove(file);
      for (let index = 0; index < this.fileList.length; index++) {
        // console.log(file.uid, this.fileList[index].uid);
        if (file.uid == this.fileList[index].uid) {
          // console.log(2);

          // this.imgsFId.fId = this.fPhotofilelist[index].atta.fId;

          if (this.fileList[index].atta == undefined) {
            // console.log(this.fileList[index].atta, this.fileList[index].fId);
            this.recordfiles.push({
              fId: this.fileList[index].fId,
            });
          } else {
            this.recordfiles.push({
              fId: this.fileList[index].atta.fId,
            });
          }
          this.fileList.splice(index, 1);
        }
      }
    },
    // 预览
    handlePictureCardPreview(file) {
      for (let i = 0; i < this.$el.querySelectorAll(".images").length; i++) {
        if (
          file.url ===
          this.$el.querySelectorAll(".images")[i].getElementsByTagName("img")[0]
            .src
        ) {
          const viewer = this.$el.querySelectorAll(".images")[i].$viewer;
          viewer.show();
          break;
        }
      }
    },
    submitUpload() {
      this.dialogUploads = false;
      this.$emit("upFileList", this.fileList);
    },
  },
};
</script>
<style scoped>

</style>
